package com.dalei.vdserver.dao;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;
import java.util.Set;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.dalei.vdserver.model.Images;

public class ImagesDaoImpl extends JdbcDaoSupport implements ImagesDao {

	@Override
	public int[] addImages(Images images) {
		// TODO Auto-generated method stub
		final String sql = "INSERT INTO vds_images (_fid, _imageId, _imageData)"
				+ "VALUES (?, ?, ?)";
		final int fid = images.getFid();
		final Map<Integer, byte[]> imagesMap = images.getImages(); 
		
		Set<Integer> keySet = imagesMap.keySet();
		final Integer[] keys = new Integer[keySet.size()];
		keySet.toArray(keys);
		int[] rowAffected = null;
		try {
			rowAffected = getJdbcTemplate().batchUpdate(sql,
					new BatchPreparedStatementSetter() {

						@Override
						public void setValues(PreparedStatement ps, int i)
								throws SQLException {
							// TODO Auto-generated method stub
							ps.setInt(1, fid);
							ps.setInt(2, keys[i]);
							InputStream in = new ByteArrayInputStream(imagesMap
									.get(keys[i]));
							ps.setBinaryStream(3, in);
						}

						@Override
						public int getBatchSize() {
							// TODO Auto-generated method stub
							return imagesMap.size();
						}
			});
		} catch (DataAccessException e) {
			// TODO: handle exception
			e.printStackTrace();
			clearImages(fid);
			return null;
		}
		return rowAffected;
	}

	@Override
	public int clearImages(int fid) {
		// TODO Auto-generated method stub
		final String sql = "DELETE * FROM vds_images WHERE _fid=?";
		int rowAffected = 0;
		try {
			rowAffected = getJdbcTemplate().update(sql, new Object[] { fid });
		} catch (DataAccessException e) {
			// TODO: handle exception
			e.printStackTrace();
			return -1;
		}
		return rowAffected;
	}
}
